package com.aruba.rtmppushapplication.push;

import android.app.Activity;
import android.hardware.Camera;
import android.view.SurfaceHolder;

import com.aruba.rtmppushapplication.push.natives.LiveStateChangeListener;
import com.aruba.rtmppushapplication.push.natives.NativePush;
import com.aruba.rtmppushapplication.push.params.AudioParams;
import com.aruba.rtmppushapplication.push.params.VideoParams;

import java.lang.ref.WeakReference;

/**
 * 直播推流工具类
 * Created by aruba on 2021/1/12.
 */
public class PushHelper {
    //显示摄像头画面的surface
    private SurfaceHolder surfaceHolder;
    //音频推流
    private AudioPush audioPush;
    //视频推流
    private VideoPush videoPush;
    private WeakReference<Activity> activity;
    //native层对象
    private NativePush nativePush;

    public PushHelper(Activity activity, SurfaceHolder surfaceHolder) {
        this.activity = new WeakReference<>(activity);
        this.surfaceHolder = surfaceHolder;
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        nativePush = new NativePush();
        //设置回调
        nativePush.setLiveStateChangeListener(new LiveStateChangeListener() {
            @Override
            public void onErrorPusher(int code) {
                videoPush.stopPush();
                audioPush.stopPush();
            }

            @Override
            public void onStartPusher() {
                //等待rtmp连接开启后，再开始推视频和音频
                videoPush.startPush();
                audioPush.startPush();
            }

            @Override
            public void onStopPusher() {
                videoPush.stopPush();
                audioPush.stopPush();
            }
        });
        
        //初始化视频参数
        VideoParams videoParams = new VideoParams.Builder()
                .videoSize(1920, 1080)
                .bitrate(960000)
                .cameraId(Camera.CameraInfo.CAMERA_FACING_BACK)
                .build();
        videoPush = new VideoPush(activity.get(), videoParams, surfaceHolder);
        videoPush.setNativePush(nativePush);
        
        //初始化音频参数
        AudioParams audioParams = new AudioParams.Builder()
                .channel(1)
                .sampleRate(44100)
                .build();
        audioPush = new AudioPush(audioParams);
        audioPush.setNativePush(nativePush);

        videoPush.init();
        audioPush.init();
    }

    /**
     * 开始推流
     *
     * @param url 服务器地址
     */
    public void startPush(String url) {
        nativePush.startPush(url);
    }

    /**
     * 停止推流
     */
    public void stopPush() {
        nativePush.stopPush();
    }

    /**
     * 切换摄像头
     */
    public void swtichCamera() {
        if (videoPush != null)
            videoPush.swtichCamera();
    }
}
